from PyQt5.QtCore import Qt, QAbstractTableModel, QModelIndex, QVariant
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableView, QVBoxLayout, QWidget, QHeaderView


class CustomTableModel(QAbstractTableModel):
    def __init__(self, headers, data=None):
        super().__init__()
        self._data = data or []
        self._headers = headers

    def rowCount(self, parent=QModelIndex()):
        return len(self._data)

    def columnCount(self, parent=QModelIndex()):
        return len(self._headers)

    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.DisplayRole:
            return self._data[index.row()][index.column()]
        return QVariant()

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.DisplayRole and orientation == Qt.Horizontal:
            return self._headers[section]
        return QVariant()

    def setData(self, index, value, role=Qt.EditRole):
        if role == Qt.EditRole:
            self._data[index.row()][index.column()] = value
            self.dataChanged.emit(index, index, [Qt.DisplayRole])
            return True
        return False

    def insertRows(self, row, count, parent=QModelIndex()):
        self.beginInsertRows(parent, row, row + count - 1)
        for _ in range(count):
            self._data.insert(row, [None] * len(self._headers))
        self.endInsertRows()
        return True

    def removeRows(self, row, count, parent=QModelIndex()):
        self.beginRemoveRows(parent, row, row + count - 1)
        del self._data[row:row + count]
        self.endRemoveRows()
        return True

    def updateData(self, data):
        self.beginResetModel()
        self._data = data
        self.endResetModel()


class TableInfoManager:
    def __init__(self, parent):
        self.parent = parent
        self.node_info_table = self.parent.node_info_table
        headers = ['当前节点', '父节点', '子节点']
        data = [
            ['', '', ''],
        ]
        self.model = CustomTableModel(headers, data)
        self.node_info_table.setModel(self.model)

        self.node_info_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

    def update_table_data(self, new_data):
        self.model.updateData(new_data)
